<?php

namespace App\Http\Controllers;

use App\Helper\Http\StatusCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    public function success($data = NULL): JsonResponse
    {
        $this->parseNull($data);
        return self::returnJson($data);
    }

    public function error($msg): JsonResponse
    {
        return self::returnJson("", StatusCode::ERROR, $msg);
    }

    private function returnJson($data = [], $code = StatusCode::SUCCESS, $msg = 'success'): JsonResponse
    {
        $json['code'] = $code;
        $json['msg'] = $msg;
        $json['data'] = $data;
        return response()->json($json);
    }

    #  如果返回的数据中有 null 则那其值修改为空 （安卓和IOS 对null型的数据不友好，会报错）
    private function parseNull(&$data)
    {
        if (is_array($data)) {
            foreach ($data as &$v) {
                $this->parseNull($v);
            }
        } else {
            if (is_null($data)) {
                $data = "";
            }
        }
    }
}
